package com.itmck.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.itmck.dao.SpringSecurityUserMapper;
import com.itmck.pojo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/11/19 10:19
 * <p>
 * <p>
 * 自定义一个CustomUserDetailService类实现接口UserDetailsService,重写loadUserByUsername方法,用于返回用户信息给springSecurity
 **/
@Slf4j
@Component
public class CustomUserDetailService implements UserDetailsService {

    @Resource
    private SpringSecurityUserMapper springSecurityUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //通过username获取用户的信息
        UserInfo userInfo = new LambdaQueryChainWrapper<>(springSecurityUserMapper)
                .eq(UserInfo::getUsername, username)
                .one();
        if (userInfo == null) {
            throw new UsernameNotFoundException("not found");
        }


        //这里由于我建表的时候为了方便将角色按照字符串+","入库 如 "admin,normal"  所以进行切割处理.也可以新建一个角色表
        String role = userInfo.getRole();
        List<String> split = StrUtil.split(role, ',');
        //定义权限列表.
        // 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
        List<GrantedAuthority> authorities = split.stream()
                .map(dto -> new SimpleGrantedAuthority("ROLE_" + dto))
                .collect(Collectors.toList());
        User userDetails = new User(userInfo.getUsername(), userInfo.getPassword(), authorities);
        log.info("当前用户:{}", userDetails);
        return userDetails;
    }
}
